import { ref, onMounted, getCurrentInstance, watch } from 'vue'
import { defineStore } from 'pinia'
// 导入mapgis查询api
import Query from '@/mapgis-api/Query'
import { setLineStyle, setAreaStyle } from '@/ol-api/index'
import createDraw from '@/ol-api/createDraw'
import { asyncGetDocInfo } from '@/mapgis-api/asyncGetDocInfo'
import { getReport } from '@/request'
import setMarkerStyle from '@/ol-api/setMarkerStyle'
// 导入icon图片
import red from '@/img/marker_red.png'
import green from '@/img/marker_green.png'
import yellow from '@/img/marker_yellow.png'
//导入监控视频
import video1 from '@/img/video/video1.mp4'
import video2 from '@/img/video/video2.mp4'

import Point from '@/mapgis-api/Point'

export const useMapgisStore = defineStore('mapgis', () => {
  /* ===============================侯佳豪==================================================== */
  /* ====================================================================================== */

  /* ===============================谭海林==================================================== */
  const { proxy } = getCurrentInstance()

  const popupContent = ref() //弹出框内容
  const catalogList = ref([]) //目录列表
  const userType = ref('') //类型
  let docLayer //文档图层
  let draw = null //画笔
  let popup //popup弹出框

  /* 公用属性 */
  const service = {
    name: 'guanggu',
    layerId: [2],
  }

  onMounted(async () => {
    const $map = proxy.$map

    //mapgis文档图层
    userType.value = localStorage.getItem('type')
    if (userType.value == 'common') {
      docLayer = new Zondy.Map.Doc('', 'guanggu', {
        crossOrigin: 'anonymous',
        layers: 'exclude:0,3',
      })
    } else {
      docLayer = new Zondy.Map.Doc('', 'guanggu', {
        crossOrigin: 'anonymous',
      })
    }

    //popup弹出框
    popup = new ol.Overlay({
      element: document.querySelector('#popup'),
      positioning: 'bottom-center',
      stopEvent: false,
      offset: [0, -5],
    })

    $map.addLayer(docLayer)

    $map.addLayer(lineLayer)
    $map.addLayer(polygonLayer)
    proxy.$map.addLayer(signLayer)

    //获取目录列表
    const res = await asyncGetDocInfo('guanggu')
    res.value.forEach((item) => {
      let { GeomType, LayerIndex, Name } = item
      catalogList.value.push({
        type: GeomType,
        index: LayerIndex,
        name: Name,
        checked: true,
      })
    })
  })

  //实时路况图层
  const realTimeTrafficLayer = new ol.layer.Vector({
    source: new ol.source.Vector({}),
  })

  let toggle = false
  //实时路况查询方法
  const realTimeTraffic = () => {
    toggle = !toggle
    //设置点击切换实时路况图层显示
    if (toggle) {
      //获取道路信息中的车流量数据
      const service = {
        name: 'guanggu',
        layerId: 1,
      }
      Query.queryByLayerId({
        service,
        success: (feature) => {
          //根据车流量大小设置不同颜色
          feature.forEach((item) => {
            var color = null
            if (item.values_.values_.车流量 < 1000) {
              color = 'green'
            } else if (item.values_.values_.车流量 < 1500) {
              color = 'yellow'
            } else {
              color = 'red'
            }
            item.setStyle(setLineStyle({ color: color, width: 4 }))
          })
          realTimeTrafficLayer.getSource().addFeatures(feature)
          //添加实时路况图层
          proxy.$map.addLayer(realTimeTrafficLayer)
        },
      })
    } else {
      //清除实时路况图层
      proxy.$map.removeLayer(realTimeTrafficLayer)
    }
  }

  /* 工具箱相关方法 */

  //测量工具函数
  const measure = ({ type, source }) => {
    if (draw) {
      proxy.$map.removeInteraction(draw)
    }
    draw = createDraw({
      type,
      source,
    })
    proxy.$map.addInteraction(draw)
    draw.on('drawend', (e) => {
      if (popup) {
        proxy.$map.removeOverlay(popup)
      }
      proxy.$map.addOverlay(popup)
      //获取测量结果
      let position
      if (type == 'LineString') {
        const points = e.feature.getGeometry().getCoordinates()
        const line = turf.lineString(points)
        //最后一个点作为测量结果
        position = e.feature.getGeometry().getCoordinates()[points.length - 1]
        const length = turf.length(line, { units: 'meters' })
        popupContent.value =
          length > 1000
            ? `${(length / 1000).toFixed(2)}km`
            : `${length.toFixed(2)}m`
      } else if (type == 'Polygon') {
        const points = e.feature.getGeometry().getCoordinates()[0]

        const polygon = turf.polygon([points])
        //计算中心点
        const center = turf.center(polygon)
        position = center.geometry.coordinates
        //计算面积
        const area = turf.area(polygon)

        popupContent.value = `${(area / 10000).toFixed(2)}km²`
      }
      //显示测量结果
      popup.setPosition(position)
    })
  }
  //测量距离图层
  const lineLayer = new ol.layer.Vector({
    source: new ol.source.Vector({}),
    style: setLineStyle({ width: 4, color: 'rgb(0, 153, 255)' }),
  })
  //测量距离方法
  const measureDistance = () => {
    measure({ type: 'LineString', source: lineLayer.getSource() })
  }
  //测量区域图层
  const polygonLayer = new ol.layer.Vector({
    source: new ol.source.Vector({}),
    style: setAreaStyle({ stroke: 'rgb(0, 153, 255)', width: 4 }),
  })
  //测量区域方法
  const measureArea = () => {
    measure({ type: 'Polygon', source: polygonLayer.getSource() })
  }

  //关闭测量
  const closeMeasure = () => {
    proxy.$map.removeInteraction(draw)
    draw = null
    popupContent.value = ''
    proxy.$map.removeOverlay(popup)
    lineLayer.getSource().clear()
    polygonLayer.getSource().clear()
    proxy.$map.removeLayer(realTimeTrafficLayer)
  }

  //导出图片
  function exportImg() {
    proxy.$map.once('postcompose', function (event) {
      const canvas = event.context.canvas
      canvas.toBlob(function (blob) {
        saveAs(blob, 'map.png')
      })
    })
    proxy.$map.renderSync()
  }

  //图层目录
  const CheckCatalogClick = (index, checked) => {
    docLayer.setLayerStatus(index, checked ? 'include' : 'exclude')
  }

  //标注图层
  const signLayer = new ol.layer.Vector({
    source: new ol.source.Vector({}),
  })
  //添加icon标注工具函数
  const addIcon = (features) => {
    features.forEach((item) => {
      let url = null
      if (item.values_.values_.处理状态 == 0) {
        url = red
      } else if (item.values_.values_.处理状态 == 1) {
        url = yellow
      } else {
        url = green
      }
      item.setStyle(setMarkerStyle(url))
    })
    signLayer.getSource().addFeatures(features)
  }

  //拉框查询工具函数(默认使用矩形拉框Box)
  const query = ({ type = 'Box' }) => {
    if (draw) {
      proxy.$map.removeInteraction(draw)
    }

    draw = createDraw({
      type,
      source: signLayer.getSource(),
      success: (feature) => {
        let service = {
          name: 'guanggu',
          layerId: 2,
        }
        let geometry = feature.getGeometry()

        //清空标注图层
        signLayer.getSource().clear()
        Query.queryByGeom({
          type,
          geometry,
          service,
          success: (feature) => {
            addIcon(feature)
            proxy.$map.on('click', (e) => {
              const features = proxy.$map.forEachFeatureAtPixel(
                e.pixel,
                function (feature, layer) {
                  return feature
                }
              )
              if (features !== undefined) {
                if (features.values_.values_) {
                  popupContent.value = features.values_.values_
                  popupContent.value.type = userType.value
                  const geometry = features.getGeometry()
                  const coord = geometry.getCoordinates()[0]
                  popup.setPosition(coord)
                  proxy.$map.addOverlay(popup)
                } else {
                  popupContent.value = ''
                  popup.setPosition(undefined)
                }
              } else {
                popupContent.value = ''
                popup.setPosition(undefined)
              }
            })
          },
        })
      },
    })
    proxy.$map.addInteraction(draw)
    draw.on('drawend', (e) => {
      proxy.$map.removeInteraction(draw)
      draw = null
    })
  }

  //点查询信息
  const queryByClick = () => {
    proxy.$map.on('click', (e) => {
      const position = e.coordinate
      // console.log(position)

      Query.queryByPnt({
        position,
        service,
        success: (feature) => {
          console.log(feature)

          if (feature !== null) {
            //清空标注图层
            signLayer.getSource().clear()
            addIcon(feature)

            proxy.$map.addOverlay(popup)
            const geometry = feature[0].getGeometry()
            const coord = geometry.getCoordinates()[0]
            popup.setPosition(coord)

            popupContent.value = feature[0].values_.values_
            popupContent.value.type = userType.value
          } else {
            popupContent.value = ''
            popup.setPosition(undefined)
            proxy.$map.removeOverlay(popup)
          }
        },
      })
    })
  }

  //关闭拉框查询
  const closeQuery = () => {
    proxy.$map.removeInteraction(draw)
    draw = null
    popupContent.value = ''
    proxy.$map.removeOverlay(popup)
    signLayer.getSource().clear()
    proxy.$map.removeEventListener('click')
  }

  //事件搜索查询
  const queryBySearch = (inputValue) => {
    const value = inputValue
    const where = {
      key: '事件类型',
      value,
    }
    Query.queryByAttr({
      where,
      service,
      success: (feature) => {
        if (feature == null) {
          ElMessage.error('未查询到相关事件')
          return
        }
        //清空标注图层
        signLayer.getSource().clear()
        addIcon(feature)

        proxy.$map.on('click', (e) => {
          proxy.$map.un('click')

          const feature = proxy.$map.forEachFeatureAtPixel(
            e.pixel,
            function (feature, layer) {
              return feature
            }
          )
          if (feature) {
            proxy.$map.addOverlay(popup)
            const geometry = feature.getGeometry()
            const coord = geometry.getCoordinates()[0]
            popup.setPosition(coord)

            popupContent.value = feature.values_.values_
            //添加type属性
            popupContent.value.type = userType.value
          } else {
            popupContent.value = ''
            popup.setPosition(undefined)
            proxy.$map.removeOverlay(popup)
          }
        })
      },
    })
  }
  //清除查询结果(事件未绑定)
  const clearSearch = () => {
    signLayer.getSource().clear()
    popupContent.value = ''
    proxy.$map.removeOverlay(popup)
    proxy.$map.removeEventListener('click')
  }

  // 创建热力图层
  const heatMapLayer = new ol.layer.Heatmap({
    source: new ol.source.Vector({
      features: [],
    }),

    gradient: ['#00ff00', '#ffff00', '#ff0000'], // 渐变颜色
    blur: 20,
    radius: 20,
  })

  //事件热力图
  const openHeatMap = () => {
    const service = {
      name: 'guanggu',
      layerId: [2],
    }
    Query.queryByLayerId({
      service,
      success: (feature) => {
        //过滤掉状态为0的事件
        let filterFeature = feature.filter((item) => {
          return item.values_.values_.处理状态 != 0
        })
        heatMapLayer.getSource().addFeatures(filterFeature)
        //添加热力图图层
        proxy.$map.addLayer(heatMapLayer)
      },
    })
  }

  //关闭热力图
  const closeHeatMap = () => {
    //移除热力图图层
    proxy.$map.removeLayer(heatMapLayer)
  }

  /* =====监控==== */
  //打开监控
  const openMonitor = () => {
    const service = {
      name: 'guanggu',
      layerId: [3],
    }
    Query.queryByLayerId({
      service,
      success: (feature) => {
        signLayer.getSource().clear()
        signLayer.getSource().addFeatures(feature)

        feature.forEach((item) => {
          item.setStyle(setMarkerStyle(red))
        })

        //添加点击事件
        proxy.$map.on('click', (e) => {
          const features = proxy.$map.forEachFeatureAtPixel(
            e.pixel,
            function (feature, layer) {
              return feature
            }
          )
          if (features !== undefined) {
            proxy.$map.addOverlay(popup)
            const geometry = features.getGeometry()
            const coord = geometry.getCoordinates()[0]
            popup.setPosition(coord)

            popupContent.value = features.values_.values_
            //添加type属性
            popupContent.value.type = 'monitor'
            //随机video
            let randomNum = Math.floor(Math.random() * 2) + 1
            if (randomNum == 1) {
              popupContent.value.video = video1
            } else {
              popupContent.value.video = video2
            }
          } else {
            popupContent.value = ''
            popup.setPosition(undefined)
            proxy.$map.removeOverlay(popup)
          }
        })
      },
    })
  }

  //关闭监控
  const closeMonitor = () => {
    signLayer.getSource().clear()
    popupContent.value = ''
    proxy.$map.removeOverlay(popup)
    proxy.$map.removeEventListener('click')
  }

  //修改属性和颜色
  // status: 0-未处理 1-处理中 2-已处理
  // fid: 要修改的要素id
  const changeFeature = ({ status, fid }) => {
    let attr = [{ name: '处理状态', type: 'short', value: status }]
    const service = {
      name: 'guanggu',
      layerId: [2],
    }

    // 修改颜色(red-6,yellow-4,green-90)
    let color = 6
    if (status == 1) {
      color = 4
    } else if (status == 2) {
      color = 90
    }
    Point.update({
      attr,
      service,
      docLayer, //可选,不传则回调会报错
      color,
      fid,
    })
  }

  // return { length, realTimeTraffic, measureDistance, closeMeasure }
  /* ======================================================================================== */
  const tableData = ref([])//所有的公告数据
  const filterData = ref()//过滤后的公告数据
  const dialogVisible = ref(false)//公告详情弹窗
  /* 上报路况事件 */
  const showNotice = ref(false)
  const CheckNoticeClick = () => {
    showNotice.value = !showNotice.value
  }
  //查看公告事件
  const showReport = ref(false)
  const CheckReportClick = async () => {
    const res = await getReport()
    console.log(res.result)
    tableData.value = res.result
    showReport.value = !showReport.value
  }
  //查看公告详细内容的事件
  const handleCheck = (index) => {
    console.log(index)
    filterData.value = tableData.value[index]
    console.log(filterData.value)
    dialogVisible.value = true
  }
  //定义一个获取图层名称的方法
  function getLayerByTitle({ map, title }) {
    /* 1, 获取地图所有的图层 */
    let layers = map.getLayers().getArray()
    // console.log(layers)
    /* 2, 过滤出title=image */
    let result = layers.find((item) => item.get('title') == title)
    /* 3, 返回结果图层 */
    return result
  }

  // return {
  //   showNotice,
  //   showReport,
  //   CheckNoticeClick,
  //   CheckReportClick,
  // }
  /* ====================================================================================== */

  /* ===============================郑旭辉==================================================== */
  /* ======================================================================================= */

  return {
    showNotice,
    showReport,
    popupContent,
    catalogList,
    CheckNoticeClick,
    CheckReportClick,
    realTimeTraffic,
    measureDistance,
    measureArea,
    closeMeasure,
    /* =========================李文雅============================= */
    getLayerByTitle,
    tableData,
    filterData,
    dialogVisible,
    handleCheck,
    

    /* =========================李文雅============================= */

    exportImg,
    CheckCatalogClick,
    query,
    queryByClick,
    closeQuery,
    queryBySearch,
    clearSearch, //未绑定
    openMonitor,
    closeMonitor,
    openHeatMap,
    closeHeatMap,
  }
})
